package com.cykj.order.service.impl;

import com.cykj.order.domain.event.OrderStatusChangeEvent;
import com.cykj.order.domain.vo.BsOrdersVo;
import com.cykj.order.mapper.OrderMapper;
import com.cykj.order.service.OrderMessageService;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 订单消息服务实现类
 * 
 * @author cykj
 * @date 2025-08-20
 */
@Service
public class OrderMessageServiceImpl implements OrderMessageService {
    
    private static final Logger logger = LoggerFactory.getLogger(OrderMessageServiceImpl.class);
    
    @Autowired
    private RocketMQTemplate rocketMQTemplate;
    
    @Autowired
    private OrderMapper orderMapper;
    
    // 主题名称常量
    private static final String ORDER_STATUS_CHANGE_TOPIC = "order-status-change";
    
    @Override
    public void sendOrderStatusChangeEvent(OrderStatusChangeEvent event) {
        try {
            if (event == null || event.getOrderId() == null) {
                logger.warn("订单状态变更事件为空或订单ID为空，跳过发送");
                return;
            }
            
            // 发送消息到RocketMQ
            rocketMQTemplate.convertAndSend(ORDER_STATUS_CHANGE_TOPIC, event);
            
            logger.info("订单状态变更事件发送成功: orderId={}, oldStatus={}, newStatus={}", 
                       event.getOrderId(), event.getOldStatus(), event.getNewStatus());
            
        } catch (Exception e) {
            logger.error("发送订单状态变更事件失败: orderId=" + event.getOrderId(), e);
            // 这里可以考虑重试机制或者写入失败队列
        }
    }
    
    @Override
    public void sendOrderStatusChangeEvent(Long orderId, Integer oldStatus, Integer newStatus, String operator) {
        try {
            // 获取订单详情用于构建完整事件
            BsOrdersVo orderInfo = orderMapper.selectOrderVoById(orderId);
            
            if (orderInfo == null) {
                logger.warn("订单不存在，无法发送状态变更事件: orderId=" + orderId);
                return;
            }
            
            // 构建事件对象
            OrderStatusChangeEvent event = new OrderStatusChangeEvent();
            event.setOrderId(orderId);
            event.setOrderNumber(orderInfo.getOrderNumber());
            event.setUserId(orderInfo.getUserId());
            event.setShopId(orderInfo.getShopId());
            event.setOldStatus(oldStatus);
            event.setNewStatus(newStatus);
            event.setTotalAmount(orderInfo.getTotalAmount());
            event.setUserPhone(orderInfo.getUserPhone());
            event.setDeliveryAddress(orderInfo.getDeliveryAddress());
            event.setOperator(operator);
            
            // 发送事件
            sendOrderStatusChangeEvent(event);
            
        } catch (Exception e) {
            logger.error("构建并发送订单状态变更事件失败: orderId=" + orderId, e);
        }
    }
}
